package com.googlecode.placesapiclient.client.parser.impl;

import com.googlecode.placesapiclient.client.entity.PlaceDetails;
import com.googlecode.placesapiclient.client.exception.ErrorCode;
import com.googlecode.placesapiclient.client.exception.ErrorCodeException;
import com.googlecode.placesapiclient.client.parser.JSONParser;
import com.googlecode.placesapiclient.client.util.Converter;
import org.apache.log4j.Logger;
import org.json.JSONObject;

/**
 */
public class PlaceDetailsParser implements JSONParser {

    private static final Logger logger = Logger.getLogger(PlaceDetailsParser.class.getName());

    public static final String RESULT = "result";

    @Override
    @SuppressWarnings("unchecked")
    public PlaceDetails parse(JSONObject jsonObject) throws ErrorCodeException {

        if (!jsonObject.has(RESULT)) {
            throw new ErrorCodeException(ErrorCode.INVALID_JSON_OBJECT, "Invalid JSONObject element");
        }
        try {
            JSONObject resultObject = jsonObject.getJSONObject(RESULT);

            PlaceDetails placeDetails = Converter.convertJsonToPlaceDetails(resultObject);
            logger.info(placeDetails.toString());
            return placeDetails;

        } catch (Throwable th) {
            logger.error("Error during parsing JSONObject", th);
            throw new ErrorCodeException(ErrorCode.INVALID_JSON_OBJECT, "Invalid JSONObject element");
        }
    }
}
